﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Menu;
using B.S.BasicData.Api.Read.DTOS;
using B.S.BasicData.Domain.Entity;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.Menu
{
    public class GetMenuTreeHandler : IRequestHandler<GetMenuTreeCommand, ApiResult<List<MenuTreeDto>>>
    {
        private readonly IBaseRepository<PathModel> _menuRepository;
        private readonly IMapper _mapper;

        public GetMenuTreeHandler(IBaseRepository<PathModel> menuRepository, IMapper mapper)
        {
            _menuRepository = menuRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取级联菜单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<List<MenuTreeDto>>> Handle(GetMenuTreeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<MenuTreeDto>> result = new ApiResult<List<MenuTreeDto>>();

            // 一次性加载所有菜单数据到内存
            var allMenus = _menuRepository.GetAll().Where(p => p.IsDelete == false).ToList();

            // 使用预加载的数据构建菜单树
            result.Data = BuildMenuTree(allMenus, 0);
            result.Code = StatusEnum.OK;
            result.Message = "查询成功";
            return Task.FromResult(result);
        }

        private List<MenuTreeDto> BuildMenuTree(List<PathModel> allMenus, long parentId)
        {
            var children = allMenus.Where(m => m.PartentId == parentId).ToList();
            var menuDtos = _mapper.Map<List<MenuTreeDto>>(children);

            foreach (var item in menuDtos)
            {
                item.Children = BuildMenuTree(allMenus, item.Id);
            }

            return menuDtos;
        }
    }
}
